#!/bin/bash

build_hook() {
	add_module cdrom
	add_module loop
	add_module overlay
	
	add_file /lib/udev/rules.d/60-cdrom_id.rules
	         
	add_binary /lib/udev/cdrom_id
	add_binary blockdev
	add_binary losetup
}

run_earlyhook() {
	local mod
	for mod in cdrom loop overlay; do
		modprobe $mod 2>/dev/null
	done
	
	if [ -z "$root" ]; then
		mount_handler=mount_venomiso
	fi
}

mount_venomiso() {
	newroot=$1
		
	MEDIA=/dev/disk/by-label/VenomLive
	MEDIUM=/run/initramfs/medium
	SYSTEM=/run/initramfs/system
	WRITEDIR=/run/initramfs/overlayfs/write
	WORKDIR=/run/initramfs/overlayfs/work
	sfsimg=/run/initramfs/medium/venom/venomrootfs.sfs
	listpkg=/run/initramfs/medium/venom/pkglist
	delay=${delay:-5}
	
	mkdir -p $MEDIUM $SYSTEM $WRITEDIR $WORKDIR
	
	if [ ! -e $MEDIA ]; then
		msg "wait $delay seconds..."
		sleep $delay
		if [ ! -e $MEDIA ]; then
			msg "media is not appeared even after wait $delay seconds..."
			msg "try increase delay by append 'delay=<seconds>' to boot cmdline"
			sleep 9999
		fi
	fi
	
	msg "mounting media to $MEDIUM..."
	mount -o ro $MEDIA $MEDIUM || problem
	
	if [ "$ram" = y ]; then
		msg "mounting /run/initramfs/ram to ram..."
		mkdir -p /run/initramfs/ram
		mount -t tmpfs -o "size=75%",mode=0755 ram /run/initramfs/ram || problem
		msg "copying squashfs img to /run/initramfs/ram..."
		cp $sfsimg /run/initramfs/ram/ || problem
		cp $listpkg /run/initramfs/ram/ || problem
		sfsimg=/run/initramfs/ram/venomrootfs.sfs
		listpkg=/run/initramfs/ram/listpkg
	fi
	sfs_dev=$(losetup --find --show --read-only $sfsimg)
	msg "mounting squashfs img to $SYSTEM..."
	mount -o defaults -r $sfs_dev $SYSTEM || problem

	# overlayfs mount	
	msg "mounting overlays to $newroot..."
	mount -t overlay overlay -o upperdir=$WRITEDIR,lowerdir=$SYSTEM,workdir=$WORKDIR $newroot || problem

	if [ -d $MEDIUM/virootfs/ ]; then
		msg "copying custom files to $newroot..."
		cp -aR $MEDIUM/virootfs/* $newroot/ || problem
	fi

	# Tell system to skip fsck during startup
	> $newroot/fastboot

	# Execute custom script before switch root
	if [ -f $newroot/root/custom_script.sh ]; then
		msg "running custom_script.sh script..."
		chmod +x $newroot/root/custom_script.sh
		chroot $newroot bash /root/custom_script.sh 2>/dev/null
	fi
	
	if [ "$ram" = y ]; then
		umount $MEDIUM
	fi
}
